package com.example.libowu.musicplayer;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;

public class MusicInterface extends AppCompatActivity implements View.OnClickListener,Runnable{
    private TextView textView;
    static SeekBar seekBar;
    static TextView allTime;
    static TextView time;
    private List<Music> list;
    private MainActivity mainActivity;
    private int position;
    private ImageButton start;
    private ImageButton last;
    private ImageButton next;
    private boolean isStart=false;
    private boolean isS=true;
    private boolean isWait=false;
    private int secone,mint,hour,se,min,ho,sec,mi,allT;
    private int me=1;
    static int startTime=0;
    private ImageButton play_order;
    private int p_o;
    private MusiChange musiChange;
    private int backgroundColor;
    private MainActivity.MusicChange musicChange;
    private sendObject so;
    private PlayServer.StartPlay startPlay;
    private boolean seekBarIsStart=true;
    private MusicImg musicImg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_interface);
        init();


        //加载主体配置文件
        loadTheme();
    }

    private void loadTheme() {
        RelativeLayout relativeLayout=(RelativeLayout) findViewById(R.id.music_interface);

        SharedPreferences sharedPreferences=getSharedPreferences("setTheme",AppCompatActivity.MODE_PRIVATE);
        backgroundColor=sharedPreferences.getInt("setTheme",R.drawable.background);
        relativeLayout.setBackgroundResource(backgroundColor);

    }

    @Override
    public void onBackPressed() {
        try{
            unbindService(MainActivity.startMusic);
        }catch (Exception e){
            Log.e("服务未启动","服务未启动");
        }
        seekBarIsStart=false;
        super.onBackPressed();
    }

    private void init() {
        textView=(TextView) findViewById(R.id.music_name);
        allTime=(TextView) findViewById(R.id.all_time);
        time=(TextView) findViewById(R.id.time);
        mainActivity=new MainActivity();
        start=(ImageButton) findViewById(R.id.start);
        last=(ImageButton) findViewById(R.id.last);
        next=(ImageButton) findViewById(R.id.next);
        start.setOnClickListener(this);
        last.setOnClickListener(this);
        next.setOnClickListener(this);
        play_order=(ImageButton) findViewById(R.id.play_order);
        musicImg=(MusicImg) findViewById(R.id.music_img);
        musiChange=new MusiChange();
        musiChange=new MusiChange();
        seekBar=(SeekBar) findViewById(R.id.seek_bar);
        seekBarAction();
        seekBar.setMax(MainActivity.mediaPlayer.getDuration());

        //显示歌曲信息
        countAllTime();

        //开启一个线程用于获取歌曲进度
        new Thread(this).start();
        play_order.setOnClickListener(this);

        //读取播放方式的配置,如循环,循序,随机等.
        SharedPreferences sharedPreferences=getSharedPreferences("playWay",AppCompatActivity.MODE_PRIVATE);
        p_o=sharedPreferences.getInt("playWay",0);

        //获取上一个活动的歌曲信息
        try{
            Intent intent=getIntent();
            textView.setText(intent.getStringExtra("songName"));
            position=intent.getIntExtra("songPosition",0);
            //获取对象
            list=mainActivity.list;
            if(MainActivity.mediaPlayer.isPlaying()){
                start.setImageResource(R.drawable.pause);
            }else {
                start.setImageResource(R.drawable.start);
            }
        }catch (NullPointerException e){
            start.setImageResource(R.drawable.start);
        }

        //设置播放方式图标
        setPlayImg();
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction("MUSIC_CHANGE");
        registerReceiver(musiChange,intentFilter);
    }

    private void setPlayImg() {
        switch (p_o) {
            case 1:
                play_order.setImageResource(R.drawable.order);
                break;
            case 2:
                play_order.setImageResource(R.drawable.random);
                break;
            case 3:
                play_order.setImageResource(R.drawable.loop);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        Intent intent=new Intent();
        intent.setAction("MUSIC_CHANGE");
        intent.putExtra("musicName",textView.getText().toString());
        intent.putExtra("musicPosition",position);
        sendBroadcast(intent);
        seekBarIsStart=false;
        unregisterReceiver(musiChange);
        musicImg.setStart(false);
        super.onDestroy();
    }



    //点击事件
    @Override
    public void onClick(View view) {
        try{
            switch (view.getId()){
                case R.id.start:
                    if(MainActivity.mediaPlayer.isPlaying()){
                        musicImg.setWait(true);
                        isStart=true;
                        MainActivity.mediaPlayer.pause();
                        start.setImageResource(R.drawable.start);
                        isWait=true;
                        if(musicImg.getWait()){
                            musicImg.setWait(true);
                        }
                    }else {
                        MainActivity.mediaPlayer.start();
                        start.setImageResource(R.drawable.pause);
                        if(isStart){
                            synchronized (this){
                                isWait=false;
                                this.notify();
                                isStart=false;
                            }
                        }
                        if(musicImg.getWait()){
                            musicImg.setNotific();
                        }
                    }
                    break;
                case R.id.last:
                    if(p_o==1){
                        if(MainActivity.sendPosition>0){
                            --MainActivity.sendPosition;
                        }
                        play();
                    }else if (p_o==2){
                        double p=Math.random()*list.size();
                        MainActivity.sendPosition=(int)p;
                        play();
                    }else if(p_o==3){
                        if(position>0){
                            --MainActivity.sendPosition;
                        }
                        play();
                        MainActivity.mediaPlayer.setLooping(true);
                    }
                    break;
                case R.id.next:
                    if(p_o==1){
                        if(position<list.size()){
                            ++MainActivity.sendPosition;
                        }
                        play();
                    }else if (p_o==2){
                        double p=Math.random()*list.size();
                        MainActivity.sendPosition=(int)p;

                        play();
                    }else if(p_o==3){
                        if(position<list.size()){
                            ++position;
                        }

                        play();
                        MainActivity.mediaPlayer.setLooping(true);
                    }
                    break;
                case R.id.play_order:
                    ++p_o;
                    if(p_o>3){
                        p_o=1;
                    }
                    switch (p_o){
                        case 1:
                            play_order.setImageResource(R.drawable.order);
                            break;
                        case 2:
                            play_order.setImageResource(R.drawable.random);
                            break;
                        case 3:
                            play_order.setImageResource(R.drawable.loop);
                            break;
                        default:
                            break;
                    }
                    SharedPreferences sharedPreferences=getSharedPreferences("playWay",AppCompatActivity.MODE_PRIVATE);
                    SharedPreferences.Editor editor=sharedPreferences.edit();
                    editor.putInt("playWay",p_o);
                    editor.commit();
                    break;
                default:
                    break;
            }

        }catch (NullPointerException e){
            Toast.makeText(MusicInterface.this,"未选择歌曲",Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //开启一个线程以改变进度条进度
    @Override
    public void run() {
       synchronized (this){

           while (seekBarIsStart){
               if(isWait){
                   try {
                       this.wait();
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }
               seekBar.setProgress(MainActivity.mediaPlayer.getCurrentPosition());
               Message message=new Message();
               message.what=me;
               handler.sendMessage(message);
               try {
                   Thread.sleep(300);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
       }
    }

    private Handler handler=new Handler(){
        public void handleMessage(Message message) {
            if(message.what==me){
                allT=seekBar.getProgress();
                int ho=allT/1000/3600;
                int min=allT/1000/60;
                int sec=(int)(((double)allT/1000/60-(double)min)*60);
                allTime.setText(ho+":"+min+":"+sec);
            }
        }
    };

    //拉动进度条时的动作
    private void seekBarAction() {
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                MainActivity.mediaPlayer.seekTo(seekBar.getProgress());
            }
        });
    }

    public void countAllTime(){
        textView.setText(MainActivity.list.get(MainActivity.sendPosition).getSongN());
        allT=MainActivity.mediaPlayer.getDuration();
        ho=allT/1000/3600;
        min=allT/1000/60;
        sec=(int)(((double)allT/1000/60-(double)min)*60);
        mi= (int) min;
        time.setText(ho+":"+min+":"+sec);
    }


    //歌曲改变时接收广播,并改变ui歌曲名
    class MusiChange extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("接收到广播","广播收到");
            textView.setText(intent.getStringExtra("musicName"));
            MainActivity.songName=intent.getStringExtra("musicName");
        }
    }

    public void play(){
        if(MainActivity.startMusic!=null){
            PlayServer.isNext=false;
            MainActivity.startPlay.player(MainActivity.list.get(MainActivity.sendPosition).getSongPath());
        }else {
            MainActivity.startMusic=new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                    startPlay=(PlayServer.StartPlay) iBinder;
                    startPlay.player(MainActivity.list.get(MainActivity.sendPosition).getSongPath());
                }

                @Override
                public void onServiceDisconnected(ComponentName componentName) {

                }
            };

            Intent intent=new Intent(MusicInterface.this,PlayServer.class);
            bindService(intent,MainActivity.startMusic,BIND_AUTO_CREATE);
        }
        MainActivity.songName=MainActivity.list.get(MainActivity.sendPosition).getSongN();
        seekBar.setMax(MainActivity.mediaPlayer.getDuration());
        start.setImageResource(R.drawable.pause);
        countAllTime();
    }

    @Override
    protected void onPause() {
        super.onPause();
        musicImg.setStart(false);
/*        if(!musicImg.getWait()){
            musicImg.setWait(true);
        }*/
    }

    @Override
    protected void onResume() {
        super.onResume();
        musicImg.setStart(true);
/*        if(musicImg.getWait()){
            musicImg.setNotific();
        }*/
    }
}
